<?php
class mdl_log_winlog extends ujn_model {
	protected function __construct() {
		parent::__construct();
		$this->db_name		= GAME;
		$this->tbl_name		= "`{$this->db_name}`.`" . GAME . "_winlog`";
		$this->_db			= $this->mysql();
	}
	const GET_REGISTER_REWARD			= 101;	// 註冊獎勵

	const GET_INVITE_REWARD				= 150;	// 邀請獎勵
	const GET_INVITE_REWARD_PASSIVE		= 151;	// 接受邀請獎勵

	const PAY_CHIPS						= 201;  // 支付 直冲金币
	const PAY_CHIPS_CANCEL				= 202;  // 支付 直冲金币后退单

	const INTER_ADMIN_ADD				= 250;	// 外部接口调用 . 管理员加钱
	const INTER_ADMIN_CUT				= 251;	// 外部接口调用 . 管理员扣钱
	const INTER_CALL					= 255;	// 外部接口调用

	/**
	 *
	 * 设置动态 $update: 是否执行更新操作 $wflag:0加1减
	 * @param $mid
	 * @param chips来源 $wmode
	 * @param 0加1减 $wflag
	 * @param 输赢数目 $wchips
	 * @param 环境ID,如游戏桌ID,反馈ID,礼物ID $wremark
	 * @param 附加信息:比如邀请好友的好友的sitemid,便于页面显示 $wdesc
	 * @param 设为1则真实加钱, 否则仅添加日志, 只接受1或者0, 其他任何都认为是0 $update
	 */
	function addWin( $mid, $wmode, $wflag, $wchips, $wremark, $wdesc='', $update=0 ) {
		if( ! $mid = $this->uint( $mid ) ) {
			return false;
		}

		$wmode		= $this->uint( $wmode );
		$wflag		= $this->uint( $wflag );
		$wchips		= $this->uint( $wchips );
		$update		= $this->uint( $update );
		$wremark	= $this->escape( $wremark );
		$wdesc		= $this->escape( $wdesc );
		$wtime		= NOW;

		$flag = false;
		$update && $wchips && $flag = mdl_member_info::getInstance()->addMoney( $mid, $wchips, $wflag ); //需要真实地更新钱数

		if( !$update || ( $update && $flag ) ) {

			$history_ck = mdl_ckey::getck(mdl_ckey::user_histroy, $mid);
			if(false != ( $wmode_flag = ujn::getCFG("system.winlog_wmode.$wmode") )) { //wmode对应表中包含这个, 则记录到历史记录中去
				$hist		= $this->mc()->get($history_ck);
				$hist_data	= false == $hist ? array() : json_decode($hist, true);
				$hist_count	= array_unshift($hist_data, array(
					$wmode_flag, NOW, $wchips, $wdesc
				));
				if($hist_count > 20) {
					$hist_data = array_slice($hist_data, 0, 20);
				}
				$this->mc()->set($history_ck, json_encode($hist_data), 0);
			}

			$query = "INSERT DELAYED INTO {$this->tbl_name} SET mid='$mid',wmode='$wmode',wflag='$wflag',wdesc='$wdesc',wchips='$wchips',wtime='$wtime',wremark='$wremark'";

			$this->_db->query($query);
			return $this->_db->affectedRows();
		}

		return false;
	}

	/**
	 * 单例模型
	 * @return mdl_member_winlog
	 */
	static function getInstance() {
		return parent::getInstance(__CLASS__);
	}
}